<?php
/*This file works with the information from the login form.*/
class Login extends Controller {
	function Login()
	{
		parent::Controller();
	}
	function index()
	{
		ob_start();
		$this->load->database();
		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		$data['title'] = "Farm101";
		$data['NoName'] = "Don't have a username or password?  This is in Private mode right now, when it opens up please come back to sign up.
		<br /><br />
		Please go <a href='/index.php/open/register/'>here</a> to register.
		";
		$data['heading'] = "<h2 class='centertext'>Login</h2>";
		$config = array(
		               array(
		                     'field'   => 'username',
		                     'label'   => 'Username',
		                     'rules'   => 'trim|required|xss_clean'
		                  ),
		               array(
		                     'field'   => 'password',
		                     'label'   => 'Password',
		                     'rules'   => 'trim|required|xss_clean'
		                  )
		            );
		$this->form_validation->set_rules($config);
		if ($this->form_validation->run() == FALSE)
			{
				$this->load->view('openheader', $data);
				$this->load->view('openview', $data);
			}
		else
			{
				$formUser = $_POST['username'];
				$formPass = md5($_POST['password']);
				//This next line looks for the User in the database, if it finds the person, it will have 1 match
				$query = $this->db->query("SELECT Username FROM User WHERE Username='$formUser' && Password='$formPass'");
				//If there is 1 match... display that Username (for testing's sake) and tell them they logged in
				if ($query->num_rows() > 0)
				{
				   foreach ($query->result() as $row)
				   {
				    $easyName = $row->Username;
					$newData = array(
						'Username' => $easyName,
						'Logged_in' => TRUE			
						);
					echo $easyName;
					echo "You have selected a real person in the Database, you are now <h1>logged in</h1>";
					echo "please go to: <a href='/index.php/closed/index/'>Here.</a>";
					$this->session->set_userdata($newData);
				   }
				}
				//If there is no match in the database... epic fail, they get this page.
				//This is the page displayed upon passing validation, but failing to login
				else
				{
					$data['title'] = "Farm101";
					$data['heading'] = "<h1 class='centertext'>Sorry</h1>";
					$data['info'] = "<p class=''>You have tried to login with an invalid username and password.  Please <a href='/index.php/open/index'>go back</a> and try again.</p>";
					$this->load->view('openheader', $data);
					$this->load->view('opendefault', $data);
					
				}
			}
	ob_flush();	
	}
}
?>